package wxencoder

import (
	"fmt"
	"crypto/aes"
	"crypto/cipher"
	"git.oschina.net/kyugao/gyencoder/b64"
)

func DecryptUserInfo(sessionKey, encryptedData, ivStr string) (result string, err error) {

	const (
		BlockSize = 32            // PKCS#7
	)

	aesKey, _ := b64.DecodeToBytes(sessionKey)
	ciphertext, _ := b64.DecodeToBytes(encryptedData)
	iv, _ := b64.DecodeToBytes(ivStr)

	if len(ciphertext) < BlockSize {
		err = fmt.Errorf("the length of ciphertext too short: %d", len(ciphertext))
		return
	}

	plaintext := make([]byte, len(ciphertext)) // len(plaintext) >= BLOCK_SIZE

	// 解密
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		panic(err)
	}
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(plaintext, ciphertext)

	// PKCS#7 去除补位
	amountToPad := int(plaintext[len(plaintext) - 1])
	if amountToPad < 1 || amountToPad > BlockSize {
		err = fmt.Errorf("the amount to pad is incorrect: %d", amountToPad)
		return
	}
	result = string(plaintext[:len(plaintext) - amountToPad])
	return
}
